﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using log4net;
using Matrix.Common.Utility;
using Matrix.Common.Utility.EnumToos;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.BLL
{
    public partial class OrdersBLL : BaseBLL<OrdersBLL>
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(OrdersBLL));

        #region 默认方法
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Orders model)
        {
            return OrdersDAL.Instance.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Orders model)
        {
            return OrdersDAL.Instance.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return OrdersDAL.Instance.Delete(Id);
        }
        /// <summary>
        /// 批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return OrdersDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Orders GetModel(int Id)
        {
            var ds = OrdersDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<Orders>(ds).ToList()[0];
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Orders> GetModelList(string strWhere = null)
        {
            var ds = OrdersDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<Orders>(ds).ToList();
        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 获得订单分页数据列表（后台使用）
        /// </summary>
        /// <param name="draw">分页计数器</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页数据条数</param>
        /// <param name="keyWord">关键字（收货人姓名、电话）</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="shopIds">店铺Ids</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="deliveryAccountId">配送人ID</param>
        /// <param name="colOrder">排序列</param>
        /// <param name="isMcUser">是否为商家后台用户订单列表</param>
        /// <param name="isDelivery">是否为送水工订单列表</param>
        /// <param name="isShowPlatformOrder"></param>
        /// <returns>分页数据列表</returns>
        /// <remarks>2016-07-13 万乐园 创建</remarks>
        /// <remarks>2016-09-14 lk update 订单状态为2的情况下可重复派单</remarks>
        public TableDataViewDto<ViewOrdersDto> GetPagingList(List<MagModules> allowedModules, int draw, int pageIndex, int pageSize, string keyWord,
            string orderNo, string startTime, string endTime, string shopIds, int orderStatus, int deliveryAccountId,
            string colOrder, bool isShowPlatformOrder = false, bool isMcUser = false, bool isDelivery = false)
        {
            try
            {
                var totalCount = 0;
                var list = OrdersDAL.Instance.GetPagingList(pageIndex, pageSize, ref totalCount, keyWord, orderNo, startTime, endTime, shopIds, orderStatus, deliveryAccountId, colOrder, isShowPlatformOrder, isMcUser: isMcUser);
                var theReturnList = new List<ViewOrdersDto>();
                if (list != null && list.Count > 0)
                {
                    var shopList = new List<Shops>();
                    if (!isMcUser)
                    {
                        shopList = ShopsBLL.Instance.GetModelList("Id in (" + string.Join(",", list.DistinctBy(l => l.ShopId).Select(l => l.ShopId)) + ")");
                    }
                    var mcAccountList = new List<McAccounts>();
                    if (list.Count(l => l.DeliveryAccountId > 0) > 0)
                    {
                        mcAccountList = McAccountsBLL.Instance.GetModelList("Id in (" + string.Join(",", list.FindAll(l => l.DeliveryAccountId > 0).DistinctBy(l => l.DeliveryAccountId).Select(l => l.DeliveryAccountId)) + ")");
                    }
                    var orderDetailList = OrderDetailBLL.Instance.GetModelList("OrderId in (" + string.Join(",", list.Select(l => l.Id)) + ")");
                    foreach (var o in list)
                    {
                        #region 数据库实体与前台展现实体转换
                        var shop = shopList.Find(l => l.Id == o.ShopId);

                        var temp = new ViewOrdersDto();
                        temp.Id = o.Id;
                        temp.OrderNo = o.OrderNo;
                        temp.OrderTime = o.OrderTime.ToString();
                        temp.OrderStatus = ((CommonEnum.OrderStatus)o.OrderStatus).GetDescription();
                        if (!isMcUser)
                        {
                            if (shop != null)
                            {
                                temp.ShopInfo = "店铺名称：" + shop.Name + "<br/>老板电话：" + shop.LegalPersonMobile + "<br/>店铺电话：" + shop.Tel;
                            }
                        }
                        temp.CommodityQuantity = o.CommodityQuantity;
                        temp.PayPrice = "￥" + o.PayPrice;
                        temp.CouponResume = GetOrderCouponUseResume(o.Id);

                        temp.PayWay = ((CommonEnum.OrderPayWay)o.PayWay).GetDescription();
                        if (o.PayPrice == 0 && !string.IsNullOrWhiteSpace(temp.CouponResume))
                        {
                            temp.PayWay = "电子水票（券）支付";
                        }

                        temp.ConsumerInfo = "姓名：" + o.ReceiverName + "<br/>电话：<a href='tel:" + o.ReceiverPhone + "'>" + o.ReceiverPhone + "</a><br/>地址：" + o.ReceiverAddress;

                        if (o.OrderStatus == (int)CommonEnum.OrderStatus.Canceled)
                        {
                            temp.ConsumerInfo = "<font style='color:red'>【订单已失效】</font><br/>" + temp.ConsumerInfo;
                        }
                        if (o.OrderIdCopiedFrom > 0)
                        {
                            temp.ConsumerInfo = "<font style='color:red'>【转移订单】</font><br/>" + temp.ConsumerInfo;
                        }

                        temp.Remark = o.Remark;
                        temp.AssignTime = o.AssignTime.ToString();
                        if (!isDelivery && o.DeliveryAccountId > 0)
                        {
                            var mcAccount = mcAccountList.Find(l => l.Id == o.DeliveryAccountId);
                            if (mcAccount != null)
                            {
                                temp.DeliveryInfo = "送水工：" + mcAccount.DisplayName + "<br/>电话：" + mcAccount.Mobile + "<br/>配送时间：" + o.DeliveryTime;
                            }
                        }
                        temp.ReceivingTime = o.ReceivingTime != null ? o.ReceivingTime.ToString() : null;
                        temp.FinishTime = o.FinishTime != null ? o.FinishTime.ToString() : null;
                        temp.CancelTime = o.CancelTime != null ? o.CancelTime.ToString() : null;
                        temp.RejectTime = o.RejectTime != null ? o.RejectTime.ToString() : null;
                        temp.RemindTime = o.RemindTime != null ? o.RemindTime.ToString() : null;
                        temp.ConsumerSendTime = o.ConsumerSendTime;
                        var detailList = orderDetailList.FindAll(l => l.OrderId == o.Id);
                        if (detailList.Count > 0)
                        {
                            for (var i = 0; i < detailList.Count; i++)
                            {
                                temp.CommodityInfo += detailList[i].CommodityName + "（x" + detailList[i].Quantity + "）";

                                var commodityLibInfo =
                                    CommodityLibDAL.Instance.GetCommodityInfoByAppointedShopCommodityIds(
                                        detailList[i].ShopCommodityId.ToString());

                                if (commodityLibInfo != null && commodityLibInfo.Count > 0)
                                {
                                    if (commodityLibInfo[0].IsVirtual)
                                    {
                                        temp.CommodityInfo += "<font style='color:blue'>【" +
                                                              ((o.ConsumerOrderType ==
                                                                (int)CommonEnum.ConsumerOrderType.ShopConsumerOrder &&
                                                                commodityLibInfo[0].Id == 87)
                                                                  ? "可提现"
                                                                  : "不可提现") + "】</font>";
                                    }
                                }

                                if (detailList[i].IsGift)
                                {
                                    temp.CommodityInfo += "<font style='color:red'>【赠品】</font>";
                                }
                                if (i != detailList.Count - 1)
                                {
                                    temp.CommodityInfo += "<hr/>";
                                }
                            }
                        }
                        #endregion

                        #region 后台用户操作按钮
                        temp.Action = string.Empty;
                        if (!isDelivery)
                        {
                        
                                temp.Action += "<a class='btn btn-primary' onclick=detail(" + o.Id + ");>详情</a> ";
                            
                        }
                        if (!isMcUser && o.OrderStatus == (int)CommonEnum.OrderStatus.NewOrder && o.OrderIdCopiedFrom == 0)
                        {
                           
                                temp.Action +=
                                    "<a data-target='#TransferOrderModal' data-toggle='modal' class='btn btn-info' onclick=transfer(" +
                                    o.Id + ");>转移</a> ";
                            
                        }

                        if (isMcUser) //仅商家后台用户可操作
                        {
                            switch (o.OrderStatus)
                            {
                                case (int)CommonEnum.OrderStatus.NewOrder: //等待派单
                                    if (isDelivery)
                                    {
                                        if (shop != null && shop.IsOpenOrderGrab)
                                        {
                                            //送水工可抢单
                                            temp.Action += "<a class='btn btn-info' onclick=grab(" + o.Id + ");>抢单</a> ";
                                        }
                                    }
                                    else
                                    {
                                        //店铺老板可派单
                                        temp.Action +=
                                            "<a data-target='#assignModal' data-toggle='modal' class='btn btn-info' onclick=assign(" +
                                            o.Id + ");>派单</a> ";
                                    }
                                    break;
                                case (int)CommonEnum.OrderStatus.BeingDelivered: //正在配送
                                    //送水工、老板可点击已送达
                                    temp.Action += "<a data-target='#assignModal' data-toggle='modal' class='btn btn-info' onclick=assign(" +
                                            o.Id + ");>派单</a> <a class='btn btn-success' onclick=arrived(" + o.Id + ");>已送达</a> ";
                                    break;
                                case (int)CommonEnum.OrderStatus.Arrived: //已送到
                                    //送水工、老板可点击订单完成
                                    temp.Action += "<a class='btn btn-success' onclick=complete(" + o.Id +
                                                   ");>订单完成</a> ";
                                    break;
                            }
                            if (!isDelivery && o.PayWay != (int)CommonEnum.OrderPayWay.WeChat)
                            {
                                if (o.OrderStatus != (int)CommonEnum.OrderStatus.Finished &&
                                    o.OrderStatus != (int)CommonEnum.OrderStatus.Canceled &&
                                    o.OrderStatus != (int)CommonEnum.OrderStatus.Rejected)
                                {
                                    //非在线支付可取消
                                    temp.Action +=
                                        "<a data-target='#cancelOrRejectedModal' data-toggle='modal' class='btn btn-danger' onclick=cancel(" +
                                        o.Id + ");>取消</a> ";
                                }
                                if (o.OrderStatus == (int)CommonEnum.OrderStatus.BeingDelivered ||
                                    o.OrderStatus == (int)CommonEnum.OrderStatus.Arrived)
                                {
                                    //店铺老板可退回
                                    temp.Action +=
                                        "<a data-target='#cancelOrRejectedModal' data-toggle='modal' class='btn btn-danger' onclick=back(" +
                                        o.Id + ");>退回</a> ";
                                }
                            }
                        }

                        #endregion

                        theReturnList.Add(temp);
                    }
                }
                var returnDataList = new TableDataViewDto<ViewOrdersDto>
                {
                    data = theReturnList,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };
                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error(" OrdersBLL -- GetPagingList | Exception: " + ex);
                return null;
            }
        }

        /// <summary>
        /// 分状态获取订单数量
        /// </summary>
        /// <param name="consumerId"></param>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public OrderAmountOfStatus GetConsumerOrderStatusStat(int consumerId, int orderStatus = -1)
        {
            var lsOrderStat = OrdersDAL.Instance.GetOrderAmountByStatus(true, true, false, true, false, consumerId, 0,
                orderStatus);

            var orderStatusAmount = new OrderAmountOfStatus();
            if (lsOrderStat == null)
            {
                return orderStatusAmount;
            }

            var orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.ToBePaid);
            orderStatusAmount.ToBePaidAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.NewOrder);
            orderStatusAmount.NewOrderAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.BeingDelivered);
            orderStatusAmount.BeingDeliveredAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.Arrived);
            orderStatusAmount.ArrivedAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.Finished);
            orderStatusAmount.FinishedAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.Canceled);
            orderStatusAmount.CanceledAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderAmount = lsOrderStat.FirstOrDefault(p => p.OrderStatus == (int)CommonEnum.OrderStatus.Rejected);
            orderStatusAmount.RejectedAmount = orderAmount == null ? 0 : orderAmount.OrderAmount;

            orderStatusAmount.TotalAmount = lsOrderStat.Sum(p => p.OrderAmount);

            return orderStatusAmount;
        }


        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Orders> GetOneShopAllOrders(int shopId)
        {
            return GetModelList("ShopId = " + shopId);
        }

        /// <summary>
        /// 得到一个订单信息主体
        /// </summary>
        public Orders GetOrderInfo(string orderNo)
        {
            return OrdersDAL.Instance.GetOrderInfo(orderNo);
        }

        /// <summary>
        /// 获取指定时间内立减金额总数
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public decimal GetTotalPayDiscountAmount(DateTime beginTime, DateTime endTime)
        {
            return OrdersDAL.Instance.GetTotalPayDiscountAmount(beginTime, endTime);
        }

        /// <summary>
        /// 获取订单优惠券使用信息（文字描述）
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string GetOrderCouponUseResume(int orderId)
        {
            var strCouponResume = string.Empty;
            var lsOrderCoupon = OrderCouponDAL.Instance.GetListByOrderId(orderId);
            if (lsOrderCoupon != null && lsOrderCoupon.Count > 0)
            {
                var lsOrderCouponGroupBy = from p in lsOrderCoupon
                                           group p by new { p.CouponId, p.CouponName, p.EnableCouponWithDraw }
                                               into g
                                               select new { g.Key, SumCoupon = g.Count() };
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                // ReSharper disable once PossibleMultipleEnumeration
                if (lsOrderCouponGroupBy != null && lsOrderCouponGroupBy.Any())
                {
                    // ReSharper disable PossibleMultipleEnumeration
                    foreach (var oc in lsOrderCouponGroupBy)
                    // ReSharper restore PossibleMultipleEnumeration
                    {
                        strCouponResume += oc.Key.CouponName + "(" + oc.SumCoupon + "张) <font style='color:blue'>" +
                                           (oc.Key.EnableCouponWithDraw ? "可提现" : "不可提现") + "</font><br/>";
                    }
                }
            }
            return strCouponResume;
        }

        /// <summary>
        /// 根据条件获取订单总数
        /// </summary>
        /// <remarks>2016-08-22 万乐园 创建</remarks>
        public int GetTotalCount(string strWhere = null)
        {
            return OrdersDAL.Instance.GetTotalCount(strWhere);
        }

        /// <summary>
        /// 获得导出订单数据列表
        /// </summary>
        /// <remarks>2016-08-26 万乐园 创建</remarks>
        public List<Orders> GetExportOrderList(string keyWord, string orderNo, string startTime, string endTime, string shopIds, int orderStatus)
        {
            var ds = OrdersDAL.Instance.GetExportOrderList(keyWord, orderNo, startTime, endTime, shopIds, orderStatus);
            return ServicesHelper.DataSetToIList<Orders>(ds).ToList();
        }

        /// <summary>
        /// 获取用户可操作订单列表
        /// </summary>
        /// <remarks>2016-09-06 万乐园 创建</remarks>
        public List<OuterOrderDto> GetOperableOrderList(int consumerId)
        {
            var result = new List<OuterOrderDto>();
            var ds = OrdersDAL.Instance.GetOperableOrderList(consumerId);
            var orderList = ServicesHelper.DataSetToIList<BaseOrder>(ds).ToList();
            foreach (var item in orderList)
            {
                var outerOrderDto = new OuterOrderDto
                {
                    BaseOrderInfo = item,
                    OrderId = item.OrderId,
                    OrderNo = item.OrderNo,
                    OrderDetailList = new List<OrderDetailInfo>()
                };

                var dsOrderDetail = OrderDetailDAL.Instance.GetList(" OrderId=" + item.OrderId);
                var lsOrderDetail = ServicesHelper.DataSetToIList<OrderDetailInfo>(dsOrderDetail).ToList();
                if (lsOrderDetail.Count > 0)
                {
                    outerOrderDto.OrderDetailList.Add(lsOrderDetail[0]);//返回第一条详情即可
                }
                result.Add(outerOrderDto);
            }
            return result;
        }
        #endregion
    }
}